package ysq.xyg.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import ysq.xyg.model.Member;
import ysq.xyg.service.MemberService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 手机端拦截器
 *
 * @author congcong tao
 * @date 2018/9/7 11:44
 */
public class PhoneLoginInterceptor extends HandlerInterceptorAdapter{

    @Resource
    private MemberService memberService;

    private List<String> exceptUrls;

    public List<String> getExceptUrls() {
        return exceptUrls;
    }

    public void setExceptUrls(List<String> exceptUrls) {
        this.exceptUrls = exceptUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        if(requestUri.startsWith(request.getContextPath())){
            requestUri = requestUri.substring(request.getContextPath().length(), requestUri.length());
        }
        //放行exceptUrls中配置的url
        for (String url : exceptUrls) {
            if (url.endsWith("/**")) {
                if (requestUri.startsWith(url.substring(0, url.length() - 3))) {
                    return true;
                }
            } else if (requestUri.startsWith(url)) {
                return true;
            }
        }
        String token = getRequestToken(request);
        if (StringUtils.isBlank(token)) {
            response.sendRedirect("/phone/loginPage");
            return false;
        }
        Member member = memberService.selectByPrimaryKey(token);
        if (member == null) {
            response.sendRedirect("/phone/loginPage");
            return false;
        }
        return true;
    }

    private String getRequestToken(HttpServletRequest httpRequest){
        // 从header中获取token
        String token = httpRequest.getHeader("memberId");
        // 如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = httpRequest.getParameter("memberId");
        }
        return token;
    }
}
